package com.sd.repay.realm;

import com.sd.repay.common.Constants;
import com.sd.repay.pojo.MerchantUser;
import com.sd.repay.service.MerchantService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class LoginRealm extends AuthorizingRealm {
    private static final Logger log = LoggerFactory.getLogger(LoginRealm.class);
    @Autowired
    private MerchantService merchantService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        LoginToken loginToken = (LoginToken) token;
        String userName = loginToken.getUsername();
        String oemType = loginToken.getOemType();
        String captcha = loginToken.getCaptcha();
        log.info("---->captcha:" + captcha);

        //校验图形验证码
        /*String exitCode = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.CLIENT_CAPTCHA_KEY);
        log.info("---->exitCode:" + exitCode);
        if (!captcha.equalsIgnoreCase(exitCode)) {
            throw new CaptchaException("验证码错误");
        }*/

        MerchantUser merchantUser = null;
        try {
            merchantUser = merchantService.getMerObjectByMobileAndOem(userName, oemType);
        } catch (Exception e) {
            return null;
        }
        if (merchantUser == null) {
            throw new UnknownAccountException();
        }
        String merchantStatus = merchantUser.getStatus();
        if (Constants.MERCHANT_STATUS_CLOSE.equals(merchantStatus) || Constants.MERCHANT_STATUS_CANCLE.equals(merchantStatus)) {
            throw new LockedAccountException();
        }

        String pwdDb = merchantUser.getLoginPwd();
        return new SimpleAuthenticationInfo(merchantUser, pwdDb, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection princ) {
        return null;
    }

}
